package com.example.weight.greenSeasons.compost;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class duifeiguzhangjilu extends AppCompatActivity {

    private String name, systemNameText, factory;

    private EditText stopTime, description, startTime, endTime,
            personInCharge, repairPerson, reason, method, adviser, restoreTime, examiner;

    private Integer faultId;

    @SuppressLint("DefaultLocale")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_duifeiguzhangjilu);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        Spinner systemName = findViewById(R.id.compost_fault_sysName);
        stopTime=findViewById(R.id.compost_fault_stopTime);
        description = findViewById(R.id.compost_fault_description);
        startTime=findViewById(R.id.compost_fault_startTime);
        endTime=findViewById(R.id.compost_fault_endTime);
        personInCharge = findViewById(R.id.compost_fault_personInCharge);
        repairPerson = findViewById(R.id.compost_fault_repairPerson);
        reason = findViewById(R.id.compost_fault_reason);
        method = findViewById(R.id.compost_fault_method);
        adviser = findViewById(R.id.compost_fault_adviser);
        restoreTime=findViewById(R.id.compost_fault_restoreTime);
        examiner = findViewById(R.id.compost_fault_examiner);

        String[] compost_equipment = getResources().getStringArray(R.array.compost_equipment);

        TitleBar titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) { finish(); }

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

        systemName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // 前端设置spinner内容 -> 设备名称
                systemNameText = compost_equipment[position];

                // 获取故障信息
                RequestQueue queue = Volley.newRequestQueue(duifeiguzhangjilu.this);
                String url = Config.url + "/sjq/compostProduceFault/getLastByEquipmentName";
                StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    if (!jsonObject.isNull("data")) {
                                        JSONObject data = jsonObject.getJSONObject("data");

                                        faultId = data.getInt("id");
                                        String faultTime = data.getString("faultTime");
                                        String faultContent = data.getString("faultContent");
                                        stopTime.setText(faultTime);
                                        description.setText(faultContent);
                                        stopTime.setEnabled(false);
                                        description.setEnabled(false);
                                    }

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(duifeiguzhangjilu.this,
                                "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String> map = new HashMap<>();
                        map.put("equipmentName", systemNameText);
                        Log.d("equipementname",factory);
                        map.put("factory", factory);
                        return map;
                    }
                };
                stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                        DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                queue.add(stringRequest);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        Calendar calendar=Calendar.getInstance();
        int YEAR = calendar.get(Calendar.YEAR);
        int MONTH = calendar.get(Calendar.MONTH);
        int DAY = calendar.get(Calendar.DAY_OF_MONTH);
        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        int MINUTE = calendar.get(Calendar.MINUTE);
        stopTime.setText(new StringBuilder()
                .append(YEAR)
                .append("/")
                .append((MONTH + 1) < 10 ? "0"
                        + (MONTH + 1) : (MONTH + 1))
                .append("/")
                .append((DAY < 10) ? "0" + DAY : DAY)
                .append(" ")
                .append(String.format("%02d",HOUR))
                .append(":")
                .append(String.format("%02d",MINUTE)));
        stopTime.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                @SuppressLint({"DefaultLocale", "ResourceType"})
                DatePickerDialog datePickerDialog = new DatePickerDialog(duifeiguzhangjilu.this, 2, (view1, year, month, day) -> {
                    // 更新EditText控件日期 小于10加0
                    TimePickerDialog timePickerDialog = new TimePickerDialog(duifeiguzhangjilu.this, 2, (view11, hourOfDay, minute) -> {
                        //  这个方法是得到选择后的 小时、分钟，分别对应着三个参数 —   hourOfDay、minute
                        stopTime.setText(new StringBuilder()
                                .append(year)
                                .append("/")
                                .append((month + 1) < 10 ? "0"
                                        + (month + 1) : (month + 1))
                                .append("/")
                                .append((day < 10) ? "0" + day : day)
                                .append(" ")
                                .append(String.format("%02d",hourOfDay))
                                .append(":")
                                .append(String.format("%02d",minute)));
                    }, HOUR, MINUTE, true);
                    timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
                        if (which == DialogInterface.BUTTON_NEGATIVE) {
                            //取消操作
                            stopTime.clearFocus();
                        }
                    });
                    timePickerDialog.show();
                }, YEAR, MONTH, DAY);
                datePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
                    if (which == DialogInterface.BUTTON_NEGATIVE) {
                        //取消操作
                        stopTime.clearFocus();
                    }
                });
                datePickerDialog.show();
            }
        });
        startTime.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                @SuppressLint({"DefaultLocale", "ResourceType"})
                DatePickerDialog datePickerDialog = new DatePickerDialog(duifeiguzhangjilu.this, 2, (view1, year, month, day) -> {
                    // 更新EditText控件日期 小于10加0
                    TimePickerDialog timePickerDialog = new TimePickerDialog(duifeiguzhangjilu.this, 2, (view11, hourOfDay, minute) -> {
                        //  这个方法是得到选择后的 小时、分钟，分别对应着三个参数 —   hourOfDay、minute
                        startTime.setText(new StringBuilder()
                                .append(year)
                                .append("/")
                                .append((month + 1) < 10 ? "0"
                                        + (month + 1) : (month + 1))
                                .append("/")
                                .append((day < 10) ? "0" + day : day)
                                .append(" ")
                                .append(String.format("%02d",hourOfDay))
                                .append(":")
                                .append(String.format("%02d",minute)));
                    }, HOUR, MINUTE, true);
                    timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
                        if (which == DialogInterface.BUTTON_NEGATIVE) {
                            //取消操作
                            startTime.clearFocus();
                        }
                    });
                    timePickerDialog.show();
                }, YEAR, MONTH, DAY);
                datePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
                    if (which == DialogInterface.BUTTON_NEGATIVE) {
                        //取消操作
                        startTime.clearFocus();
                    }
                });
                datePickerDialog.show();
            }
        });
        endTime.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                @SuppressLint({"DefaultLocale", "ResourceType"})
                DatePickerDialog datePickerDialog = new DatePickerDialog(duifeiguzhangjilu.this, 2, (view1, year, month, day) -> {
                    // 更新EditText控件日期 小于10加0
                    TimePickerDialog timePickerDialog = new TimePickerDialog(duifeiguzhangjilu.this, 2, (view11, hourOfDay, minute) -> {
                        //  这个方法是得到选择后的 小时、分钟，分别对应着三个参数 —   hourOfDay、minute
                        endTime.setText(new StringBuilder()
                                .append(year)
                                .append("/")
                                .append((month + 1) < 10 ? "0"
                                        + (month + 1) : (month + 1))
                                .append("/")
                                .append((day < 10) ? "0" + day : day)
                                .append(" ")
                                .append(String.format("%02d",hourOfDay))
                                .append(":")
                                .append(String.format("%02d",minute)));
                    }, HOUR, MINUTE, true);
                    timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
                        if (which == DialogInterface.BUTTON_NEGATIVE) {
                            //取消操作
                            endTime.clearFocus();
                        }
                    });
                    timePickerDialog.show();
                }, YEAR, MONTH, DAY);
                datePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
                    if (which == DialogInterface.BUTTON_NEGATIVE) {
                        //取消操作
                        endTime.clearFocus();
                    }
                });
                datePickerDialog.show();
            }
        });
        restoreTime.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                @SuppressLint({"DefaultLocale", "ResourceType"})
                DatePickerDialog datePickerDialog = new DatePickerDialog(duifeiguzhangjilu.this, 2, (view1, year, month, day) -> {
                    // 更新EditText控件日期 小于10加0
                    TimePickerDialog timePickerDialog = new TimePickerDialog(duifeiguzhangjilu.this, 2, (view11, hourOfDay, minute) -> {
                        //  这个方法是得到选择后的 小时、分钟，分别对应着三个参数 —   hourOfDay、minute
                        restoreTime.setText(new StringBuilder()
                                .append(year)
                                .append("/")
                                .append((month + 1) < 10 ? "0"
                                        + (month + 1) : (month + 1))
                                .append("/")
                                .append((day < 10) ? "0" + day : day)
                                .append(" ")
                                .append(String.format("%02d",hourOfDay))
                                .append(":")
                                .append(String.format("%02d",minute)));
                    }, HOUR, MINUTE, true);
                    timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
                        if (which == DialogInterface.BUTTON_NEGATIVE) {
                            //取消操作
                            restoreTime.clearFocus();
                        }
                    });
                    timePickerDialog.show();
                }, YEAR, MONTH, DAY);
                datePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
                    if (which == DialogInterface.BUTTON_NEGATIVE) {
                        //取消操作
                        restoreTime.clearFocus();
                    }
                });
                datePickerDialog.show();
            }
        });
    }

    @SuppressLint({"DefaultLocale", "ResourceType"})
    public void chooseStopDate(View view) {
        Calendar calendar=Calendar.getInstance();
        int YEAR = calendar.get(Calendar.YEAR);
        int MONTH = calendar.get(Calendar.MONTH);
        int DAY = calendar.get(Calendar.DAY_OF_MONTH);
        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        int MINUTE = calendar.get(Calendar.MINUTE);
        new DatePickerDialog(this, 2, (view1, year, month, day) -> {
                    // 更新EditText控件日期 小于10加0
                    new TimePickerDialog(this, 2, (view11, hourOfDay, minute) -> {
                        //  这个方法是得到选择后的 小时、分钟，分别对应着三个参数 —   hourOfDay、minute
                        stopTime.setText(new StringBuilder()
                                .append(year)
                                .append("/")
                                .append((month + 1) < 10 ? "0"
                                        + (month + 1) : (month + 1))
                                .append("/")
                                .append((day < 10) ? "0" + day : day)
                                .append(" ")
                                .append(String.format("%02d",hourOfDay))
                                .append(":")
                                .append(String.format("%02d",minute)));
                    },
                    HOUR, MINUTE, true).show();
                },
                YEAR, MONTH, DAY).show();
    }

    @SuppressLint({"DefaultLocale", "ResourceType"})
    public void chooseStartDate(View view) {
        Calendar calendar=Calendar.getInstance();
        int YEAR = calendar.get(Calendar.YEAR);
        int MONTH = calendar.get(Calendar.MONTH);
        int DAY = calendar.get(Calendar.DAY_OF_MONTH);
        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        int MINUTE = calendar.get(Calendar.MINUTE);
        new DatePickerDialog(this, 2, (view1, year, month, day) -> {
                    // 更新EditText控件日期 小于10加0
                    new TimePickerDialog(this, 2, (view11, hourOfDay, minute) -> {
                        //  这个方法是得到选择后的 小时、分钟，分别对应着三个参数 —   hourOfDay、minute
                        startTime.setText(new StringBuilder()
                                .append(year)
                                .append("/")
                                .append((month + 1) < 10 ? "0"
                                        + (month + 1) : (month + 1))
                                .append("/")
                                .append((day < 10) ? "0" + day : day)
                                .append(" ")
                                .append(String.format("%02d",hourOfDay))
                                .append(":")
                                .append(String.format("%02d",minute)));
                    }, HOUR, MINUTE, true).show();

                }, YEAR, MONTH, DAY).show();
    }

    @SuppressLint({"DefaultLocale", "ResourceType"})
    public void chooseEndDate(View view) {
        Calendar calendar=Calendar.getInstance();
        int YEAR = calendar.get(Calendar.YEAR);
        int MONTH = calendar.get(Calendar.MONTH);
        int DAY = calendar.get(Calendar.DAY_OF_MONTH);
        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        int MINUTE = calendar.get(Calendar.MINUTE);
        new DatePickerDialog(this, 2, (view1, year, month, day) -> {
            // 更新EditText控件日期 小于10加0
            new TimePickerDialog(this, 2, (view11, hourOfDay, minute) -> {
                //  这个方法是得到选择后的 小时、分钟，分别对应着三个参数 —   hourOfDay、minute
                endTime.setText(new StringBuilder()
                        .append(year)
                        .append("/")
                        .append((month + 1) < 10 ? "0"
                                + (month + 1) : (month + 1))
                        .append("/")
                        .append((day < 10) ? "0" + day : day)
                        .append(" ")
                        .append(String.format("%02d",hourOfDay))
                        .append(":")
                        .append(String.format("%02d",minute)));
            }, HOUR, MINUTE, true).show();

        }, YEAR, MONTH, DAY).show();
    }

    @SuppressLint({"DefaultLocale", "ResourceType"})
    public void chooseRestoreDate(View view) {
        Calendar calendar=Calendar.getInstance();
        int YEAR = calendar.get(Calendar.YEAR);
        int MONTH = calendar.get(Calendar.MONTH);
        int DAY = calendar.get(Calendar.DAY_OF_MONTH);
        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        int MINUTE = calendar.get(Calendar.MINUTE);
        new DatePickerDialog(this, 2, (view1, year, month, day) -> {
            // 更新EditText控件日期 小于10加0
            new TimePickerDialog(this, 2, (view11, hourOfDay, minute) -> {
                //  这个方法是得到选择后的 小时、分钟，分别对应着三个参数 —   hourOfDay、minute
                restoreTime.setText(new StringBuilder()
                        .append(year)
                        .append("/")
                        .append((month + 1) < 10 ? "0"
                                + (month + 1) : (month + 1))
                        .append("/")
                        .append((day < 10) ? "0" + day : day)
                        .append(" ")
                        .append(String.format("%02d",hourOfDay))
                        .append(":")
                        .append(String.format("%02d",minute)));
            }, HOUR, MINUTE, true).show();

        }, YEAR, MONTH, DAY).show();
    }

    public void save(View view) {
        if (systemNameText == null) {
            Toast.makeText(this, "请选择故障系统", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定提交吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消提交", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {
                    // 提交表单
                    RequestQueue queue = Volley.newRequestQueue(this);
                    if (faultId == null) {
                        // 填写前半部分信息
                        if(stopTime.getText().toString().equals("")) {
                            Toast.makeText(this, "请填写停机时间", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (description.getText().toString().equals("")) {
                            Toast.makeText(this, "请填写故障情况描述", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        String url = Config.url + "/sjq/compostProduceFault/addFrontPart";
                        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                                new Response.Listener<String>() {
                                    @Override
                                    public void onResponse(String response) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(response);
                                            String code = jsonObject.getString("code");

                                            if (code.startsWith("2"))
                                                Toast.makeText(duifeiguzhangjilu.this,
                                                        "提交成功", Toast.LENGTH_SHORT).show();
                                            else
                                                Toast.makeText(duifeiguzhangjilu.this,
                                                        "提交失败", Toast.LENGTH_SHORT).show();
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Toast.makeText(duifeiguzhangjilu.this,
                                        "提交失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }) {
                            @Override
                            protected Map<String, String> getParams() {
                                Map<String, String> map=new HashMap<>();
                                map.put("equipmentName", systemNameText);
                                map.put("faultTime", stopTime.getText().toString());
                                map.put("operator", name);
                                map.put("faultContent", description.getText().toString());
                                Log.d("before",factory);
                                map.put("factory", factory);
                                return map;
                            }
                        };
                        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                        queue.add(stringRequest);
                    } else {
                        // 填写后半部分信息
                        if (startTime.getText().toString().equals("")) {
                            Toast.makeText(this, "请填写维修开始时间", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (endTime.getText().toString().equals("")) {
                            Toast.makeText(this, "请填写维修结束时间", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (personInCharge.getText().toString().equals("")) {
                            Toast.makeText(this, "请填写维修负责人", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (repairPerson.getText().toString().equals("")) {
                            Toast.makeText(this, "请填写维修人员", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (reason.getText().toString().equals("")) {
                            Toast.makeText(this, "请填写故障原因分析", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (method.getText().toString().equals("")) {
                            Toast.makeText(this, "请填写维修方法", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (adviser.getText().toString().equals("")) {
                            Toast.makeText(this, "请填写方法提出人", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (restoreTime.getText().toString().equals("")) {
                            Toast.makeText(this, "请填写故障恢复时间", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (examiner.getText().toString().equals("")) {
                            Toast.makeText(this, "请填写检查人", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        String url = Config.url + "/sjq/compostProduceFault/addAfterPart";
                        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                                new Response.Listener<String>() {
                                    @Override
                                    public void onResponse(String response) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(response);
                                            String code = jsonObject.getString("code");

                                            if (code.startsWith("2")) {
                                                Toast.makeText(duifeiguzhangjilu.this,
                                                        "提交成功", Toast.LENGTH_SHORT).show();
                                            }
                                            else
                                                Toast.makeText(duifeiguzhangjilu.this,
                                                        "提交失败", Toast.LENGTH_SHORT).show();
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Toast.makeText(duifeiguzhangjilu.this,
                                        "提交失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }) {
                            @Override
                            protected Map<String, String> getParams() {
                                Map<String, String> map=new HashMap<>();
                                map.put("faultId", faultId.toString());
                                map.put("serviceTimeStart", startTime.getText().toString());
                                map.put("serviceTimeEnd", endTime.getText().toString());
                                map.put("servicemanInCharge", personInCharge.getText().toString());
                                map.put("serviceman", repairPerson.getText().toString());
                                map.put("faultReason", reason.getText().toString());
                                map.put("serviceMethod", method.getText().toString());
                                map.put("proposer", adviser.getText().toString());
                                map.put("recoverTime", restoreTime.getText().toString());
                                map.put("inspector", examiner.getText().toString());
                                Log.d("after",factory);
                                map.put("factory", factory);
                                return map;
                            }
                        };
                        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                        queue.add(stringRequest);
                    }
                }).show();
    }
}